package edu.gatech.teamrocket.models;
import java.sql.SQLException;

import android.content.SharedPreferences.Editor;

import com.j256.ormlite.dao.Dao;
import edu.gatech.teamrocket.DewApplication;

public class Auth {
	private DewApplication app;
	private static Auth instance = null;
	
    // Private constructor prevents instantiation from other classes
    private Auth(DewApplication app) {
    	// uses DewApplication as a context
    	this.app = app;
    }

    public static Auth getInstance(DewApplication app) {
    	if (instance == null) {
    		instance = new Auth(app);
    	}
    	return instance;
    }
    
    /**
     * Gets the currently logged in user. Null if not logged in.
     * @return logged in user
     */
    public User getUser() {
    	try {
	    	Dao<User, String> userDao = app.getHelper().getUserDao();
	    	String username = app.getSettings().getString("username", null);

	    	if (username != null) {
	    		return userDao.queryForId(username);
	    	} else {
	    		return null;
	    	}
    	} catch (SQLException e) {
    		throw new RuntimeException(e);
    	}
    }
    
    /**
     * Sets the currently logged in user to the given User input.
     * @param user that is currently logged in
     */
    public void setUser(User user) {
    	Editor edit = app.getSettings().edit();
    	edit.putString("username", user.getUsername());
    	edit.apply();
    }
    
    /**
     * Check if a user is currently logged in.
     * @return true if the user is logged in, false otherwise
     */
    public boolean check() {
    	if (getUser() != null) {
    		return true;
    	} else {
    		return false;
    	}
    }
    
    /**
     * Logs a user in. Returns true if the login is valid, false otherwise.
     * @param username
     * @param password
     * @return true if valid, false otherwise
     */
    public boolean login(String username, String password) {
    	try {
			Dao<User, String> userDao = app.getHelper().getUserDao();
			User user = userDao.queryForId(username);
			if (user == null || !user.getPassword().equals(password)) {
				return false;
			} else {
				setUser(user);
				return true;
			}
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
    }
    
    /**
     * Logs the user out. Removes the currently logged in user from shared settings.
     */
    public void logout() {
    	Editor edit = app.getSettings().edit();
    	edit.clear();
    	edit.apply();
    }
}